package admin

import (
	"github.com/gin-gonic/gin"
	"go-project/common/casbininit"
	"go-project/dto/requrest"
	"go-project/pkg/utils"
	"go-project/service"
	"net/http"
	"strconv"
	"strings"
)

type RolesController struct {
}

func (RolesController) List(c *gin.Context) {
	pagination := requrest.GeneratePaginationFormRequest(c)
	rolesSearchRequest := requrest.RolesSearchRequest{Pagination: &pagination}
	err := c.ShouldBind(&rolesSearchRequest)
	if err != nil {
		return
	}
	lists, count, err := service.Roles{}.FindLists(&rolesSearchRequest)
	utils.PaginationSuccess(c, count, lists, pagination)
}

func (RolesController) Add(c *gin.Context) {
	rolesInsertRequest := &requrest.RolesSInsertRequest{}
	errors := rolesInsertRequest.BindAndValidate(c)
	if errors != nil {
		return
	}
	insert_id, err := service.Roles{}.Add(rolesInsertRequest)
	if err != nil {
		utils.Error(c, utils.ERROR, "添加失败", http.StatusOK)
		return
	}
	utils.Success(c, gin.H{
		"id": insert_id,
	}, http.StatusCreated)
}
func (RolesController) Edit(c *gin.Context) {
	id, err := strconv.Atoi(c.Query("id"))
	if err != nil {
		c.HTML(http.StatusNotFound, "admin.error", gin.H{
			"error": err.Error(),
		})
		return
	}
	model, err := service.Roles{}.Get(uint(id))
	if err != nil {
		c.HTML(http.StatusBadGateway, "admin.error", gin.H{
			"error": err.Error(),
		})
		return
	}
	var permissionsCodes = make([]string, 0, 10)
	//查询该角色对于的所有权限
	role := casbininit.Enforcer.GetPermissionsForUser("role:" + model.Key)
	for _, v := range role {
		permissionsCodes = append(permissionsCodes, v[1])
	}
	ids, err := service.Permissions{}.GetIdsByCodes(permissionsCodes)
	if err != nil {
		c.HTML(http.StatusBadGateway, "admin.error", gin.H{
			"error": err.Error(),
		})
		return
	}
	var strIds string
	if len(ids) > 0 {
		strIds = strings.Join(ids, ",")
	}

	c.HTML(http.StatusOK, "roles.edit", gin.H{
		"model": model,
		"ids":   strIds,
	})
}

func (RolesController) Update(c *gin.Context) {
	rolesUpdateRequest := &requrest.RolesUpdateRequest{}
	err := rolesUpdateRequest.BindAndValidate(c)
	if err != nil {
		return
	}
	update_id, err := service.Roles{}.Update(rolesUpdateRequest)
	if err != nil {
		utils.Error(c, utils.ERROR, err.Error(), http.StatusOK)
		return
	}
	utils.Success(c, gin.H{
		"id": update_id,
	}, http.StatusOK)
}
func (RolesController) Delete(c *gin.Context) {
	value := c.Query("id")
	if value == "" {
		utils.Error(c, utils.ERROR, "id不能为空", http.StatusOK)
		return
	}
	id, err := strconv.Atoi(value)
	if err != nil {
		utils.Error(c, utils.ERROR, err.Error(), http.StatusOK)
		return
	}
	rowsAffected, err := service.Roles{}.Del(uint(id))
	if err != nil {
		utils.Error(c, utils.ERROR, err.Error(), http.StatusOK)
		return
	}
	if rowsAffected <= 0 {
		utils.Error(c, utils.ERROR, "删除失败", http.StatusOK)
	}
	utils.Success(c, gin.H{}, http.StatusNoContent)
}
func (RolesController) BatchDelete(c *gin.Context) {
	value := c.Query("ids")
	if value == "" {
		utils.Error(c, utils.ERROR, "id不能为空", http.StatusOK)
		return
	}
	ids := strings.Split(value, ",")
	var new_ids []int
	for _, id := range ids {
		id, _ := strconv.Atoi(id)
		new_ids = append(new_ids, id)
	}
	rowsAffected, err := service.Roles{}.BatchDelByIds(new_ids)
	if err != nil {
		utils.Error(c, utils.ERROR, err.Error(), http.StatusOK)
		return
	}
	if rowsAffected <= 0 {
		utils.Error(c, utils.ERROR, "删除失败", http.StatusOK)
	}
	utils.Success(c, gin.H{}, http.StatusNoContent)
}

func (RolesController) GetAuth(c *gin.Context) {
	id, err := strconv.Atoi(c.Query("id"))
	if err != nil {
		utils.Error(c, utils.ERROR, "id不能为空", http.StatusOK)
		return
	}
	model, err := service.Roles{}.Get(uint(id))
	if err != nil {
		c.HTML(http.StatusBadGateway, "admin.error", gin.H{
			"error": err.Error(),
		})
		return
	}
	var permissionsCodes = make([]string, 0, 10)
	//查询该角色对于的所有权限
	role := casbininit.Enforcer.GetPermissionsForUser("role:" + model.Key)
	for _, v := range role {
		permissionsCodes = append(permissionsCodes, v[1])
	}
	ids, err := service.Permissions{}.GetIdsByCodes(permissionsCodes)
	if err != nil {
		c.HTML(http.StatusBadGateway, "admin.error", gin.H{
			"error": err.Error(),
		})
		return
	}
	var strIds string
	if len(ids) > 0 {
		strIds = strings.Join(ids, ",")
	}
	c.HTML(http.StatusOK, "roles.auth", gin.H{
		"model": model,
		"ids":   strIds,
	})
}

func (RolesController) AuthPermissions(c *gin.Context) {
	rolesAuthPerMissionsRequest := &requrest.RolesAuthPerMissionsRequest{}
	err := rolesAuthPerMissionsRequest.BindAndValidate(c)
	if err != nil {
		return
	}
	err = service.Roles{}.DistributePermissions(rolesAuthPerMissionsRequest)
	if err != nil {
		utils.Error(c, utils.ERROR, err.Error(), http.StatusOK)
		return
	}
	utils.Success(c, gin.H{}, http.StatusNoContent)

}

func (RolesController) SelectGetList(c *gin.Context) {
	pagination := requrest.GeneratePaginationFormRequest(c)
	rolesSearchRequest := requrest.RolesSearchRequest{Pagination: &pagination}
	err := c.ShouldBind(&rolesSearchRequest)
	if err != nil {
		return
	}
	lists, count, err := service.Roles{}.FindLists(&rolesSearchRequest)
	type newRole struct {
		Key  string `json:"value"`
		Name string `json:"name"`
	}
	var newRoles = make([]newRole, 0, 10)
	for _, v := range lists {

		newRoles = append(newRoles, newRole{
			Key:  v.Key,
			Name: v.Name,
		})
	}
	utils.PaginationSuccess(c, count, newRoles, pagination)
}
